import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/bezier_bounce_footer.dart';
import 'package:flutter_easyrefresh/bezier_circle_header.dart';
import "package:flutter_easyrefresh/easy_refresh.dart";
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mall/constant/string.dart';
import 'package:mall/cust_widget/custom_tabbar.dart';
import 'package:mall/cust_widget/primary_refresher.dart';
import 'package:mall/cust_widget/sliver_persistent_delegate.dart';
import 'package:mall/entity/home_entity.dart';
import 'package:mall/page/home/category.dart';
import 'package:mall/page/home/new_product.dart';
import 'package:mall/page/home/swiper.dart';
import 'package:mall/page/home/tab/BodySpin.dart';
import 'package:mall/page/home/tab/CSV.dart';
import 'package:mall/page/home/tab/TestPage.dart';
import 'package:mall/service/home_service.dart';
import 'package:mall/utils/navigator_util.dart';
import 'package:mall/utils/shared_preferences_util.dart';
import 'package:mall/utils/string_util.dart';
import 'package:mall/utils/toast_util.dart';
import 'package:mall/widgets/cached_image.dart';
import 'package:mall/widgets/loading_dialog.dart';
import 'package:marquee_flutter/marquee_flutter.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>  with TickerProviderStateMixin {
  HomeService _homeService = HomeService();
  HomeEntity _homeEntity;
  int currentIndex = 0;

  EasyRefreshController _controller = EasyRefreshController();

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  TabController _tabbarController;

  @override
  void initState() {
    super.initState();
    SharedPreferencesUtils.getToken().then((token) {});
    _queryHomeData();
  }



  _queryHomeData() {
    _homeService.queryHomeData((success) {
      _homeEntity = success;
      _tabbarController = TabController(length: _homeEntity.floorGoodsList.length,initialIndex: currentIndex, vsync: this);
      print(_homeEntity);
      setState(() {});
      // _controller.finishRefresh();
    }, (error) {
      ToastUtil.showToast(error);
      // _controller.finishRefresh();
    });
  }

  _goSearchGoods() {
    NavigatorUtils.goSearchGoods(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(Strings.MALL), actions: <Widget>[
        IconButton(
            icon: Icon(
              Icons.search,
              color: Colors.white,
            ),
            onPressed: () => _goSearchGoods())
      ]),
      body: contentWidget(),
    );
  }


  // _queryHomeData();
  Widget contentWidget() {
    if (_homeEntity == null) {
      return LoadingDialog();
    } else {
      return PrimaryRefresher(
          onLoading: (){
            return true;
          },
          onRefresh: () {
            _queryHomeData();
            return true;
          },
          controller: _refreshController,
          child: CustomScrollView(
            slivers: [
              SliverToBoxAdapter(
                  child: SwiperView(
                      _homeEntity.banner, ScreenUtil().setHeight(360.0))),
              SliverToBoxAdapter(
                  child: Padding(
                padding: EdgeInsets.only(top: 10),
              )),
              SliverToBoxAdapter(
                child: CategoryMenu(_homeEntity.channel),
              ),
              SliverToBoxAdapter(
                child: new Container(
                  height: 30,
                  child: new MarqueeWidget(
                    text: StringUtils.toStrings(_homeEntity.recoveryTypeList),
                    textStyle: new TextStyle(fontSize: 16.0),
                    scrollAxis: Axis.horizontal,
                  ),
                ),
              ),
              buildCategory(),
              buildCategoryList(),
            ],
          ));
      //   child: Column(
      //     children: <Widget>[
      //       SwiperView(_homeEntity.banner, ScreenUtil().setHeight(360.0)),
      //       Padding(
      //         padding: EdgeInsets.only(top: 10),
      //       ),
      //       CategoryMenu(_homeEntity.channel),
      //       new Container(
      //         height: 30,
      //         child: new MarqueeWidget(
      //           text: StringUtils.toStrings(_homeEntity.recoveryTypeList),
      //           textStyle: new TextStyle(fontSize: 16.0),
      //           scrollAxis: Axis.horizontal,
      //         ),
      //       ),
      //       Container(
      //         decoration: BoxDecoration(
      //             border:
      //             Border(bottom: BorderSide(color: Colors.white))),
      //         height: MediaQuery.of(context).size.height *
      //             _homeEntity.floorGoodsList.length *
      //             1.5,
      //         width: double.infinity,
      //         margin: EdgeInsets.only(left: 1.0, right: 1.0, bottom: 4.0),
      //         child: LayoutDemo(_homeEntity.floorGoodsList),
      //       )
      //     ],
      //   ));

    }
  }






  List<Widget> buildTabList(List<FloorGoodsList> floorGoodsList) {
    return floorGoodsList
        .map((e) => Container(
              alignment: Alignment.center,
              height: 52.w,
              // color: Color(0xFFF7F8FA),
              child: Text(
                '${e.name}',
                textScaleFactor: 1,
              ),
            ))
        .toList();
  }



  Widget buildCategoryList() {
    return SliverPadding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.w),
      sliver: SliverGrid(
        gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2, //Grid按两列显示
          mainAxisSpacing: 12.w,
          crossAxisSpacing: 20.w,
          childAspectRatio: 0.62,
        ),
        delegate: new SliverChildBuilderDelegate(
              (BuildContext context, int index) {
            return Container(
                decoration: new BoxDecoration(
                  //背景Colors.transparent 透明
                  color: Colors.transparent,
                  //设置四周圆角 角度
                  borderRadius: BorderRadius.all(Radius.circular(4.0)),
                  //设置四周边框
                  border: new Border.all(width: 1, color: Color(0xFFFFFFFF)),
                ),
                child: new Center(
                  child: _getGridViewItem(context, _homeEntity.floorGoodsList[currentIndex].goodsList[index]),
                ));
          },
          childCount: _homeEntity.floorGoodsList[currentIndex].goodsList.length,
        ),
      ),
    );
  }



  _goGoodsDetail(BuildContext context, Goods goods) {
    NavigatorUtils.goGoodsDetails(context, goods.id);
  }



  Widget _getGridViewItem(BuildContext context, Goods productEntity) {
    return Container(
      child: InkWell(
        onTap: () => _goGoodsDetail(context, productEntity),
        child: Card(
          elevation: 0,
          margin: EdgeInsets.all(1.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Container(
                  margin: EdgeInsets.all(1.0),
                  child: CachedImageView(
                      ScreenUtil().setHeight(400.0),
                      ScreenUtil().setHeight(310.0),
                      productEntity.picUrl)),
              Padding(
                padding: EdgeInsets.only(top: 1.0),
              ),
              Container(
                padding: EdgeInsets.only(left: 1.0, top: 1.0),
                alignment: Alignment.centerLeft,
                child: Text(
                  productEntity.name,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: Colors.black54, fontSize: 14.0),
                ),
              ),
              Container(
                padding: EdgeInsets.only(left: 1.0, top: 1.0),
                alignment: Alignment.centerLeft,
                child: Text(
                  "￥${productEntity.retailPrice}",
                  style: TextStyle(
                    color: Colors.red,
                    fontSize: 18.0,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget buildCategory() {
    return SliverPersistentHeader(
      delegate: SliverPersistentDelegate(
        height: 100.w,
        child: Container(
          height: 100.w,
          color: Color(0xFFF7F8FA),
          child: CustomTabBar(
            controller: _tabbarController,
            // isScrollable: true,
            tabs: buildTabList(_homeEntity.floorGoodsList),
            // labelStyle: TextStyle(fontSize: 16),
            // unselectedLabelStyle: TextStyle(fontSize: 14.w),
            labelColor: Color(0xFF0AB9BE),
            unselectedLabelColor: Color(0xFF7F838F),
            indicator: CircleTabIndicator(color: Color(0xFF0AB1BA), radius: 10),
            onTap: (index) {
                setState(() {
                  currentIndex = index;
                });
            },
            // indicatorWeight: ,
          ),
        ),
      ),
      pinned: true,
    );
  }

  Widget _floorGoodsWidget(FloorGoodsList floorGoods) {
    return Container(
      child: Column(
        children: <Widget>[
          Container(
            height: 40.0,
            alignment: Alignment.center,
            child: Text(floorGoods.name),
          ),
          ProductView(floorGoods.goodsList),
        ],
      ),
    );
  }
}

// 自定义Tabbar 指示器
class CircleTabIndicator extends Decoration {
  final BoxPainter _painter;

  CircleTabIndicator({@required Color color, @required double radius})
      : _painter = _CirclePainter(color, radius);

  @override
  BoxPainter createBoxPainter([onChanged]) => _painter;
}

class _CirclePainter extends BoxPainter {
  final Paint _paint;
  final double radius;

  _CirclePainter(Color color, this.radius)
      : _paint = Paint()
          ..color = color
          ..isAntiAlias = true;

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    final Offset circleOffset = offset +
        Offset((configuration.size.width - 22) / 2,
            configuration.size.height - radius - 2);
    canvas.drawRRect(
        RRect.fromRectAndRadius(
            circleOffset & const Size(18, 3), Radius.circular(2)),
        _paint);
  }
}
